package red.yancloud.www.ui.activity

import android.content.Intent
import android.graphics.Color
import android.text.Spannable
import android.text.SpannableString
import android.text.TextUtils
import android.text.style.ForegroundColorSpan
import android.util.Log
import android.view.View
import com.alibaba.fastjson.JSONObject
import com.umeng.socialize.UMAuthListener
import com.umeng.socialize.UMShareAPI
import com.umeng.socialize.bean.SHARE_MEDIA
import com.vdurmont.emoji.EmojiParser
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.activity_register.*
import kotlinx.android.synthetic.main.title_base_head.*
import okhttp3.ResponseBody
import org.greenrobot.eventbus.EventBus
import red.yancloud.www.R
import red.yancloud.www.base.BaseActivity
import red.yancloud.www.common.Constants
import red.yancloud.www.common.MessageEvent
import red.yancloud.www.db.sharedpreference.UserInfoShardPreference
import red.yancloud.www.internet.api.RedCloudApis
import red.yancloud.www.internet.bean.Login
import red.yancloud.www.util.ActivityUtils
import red.yancloud.www.util.RegularExpression
import red.yancloud.www.util.ToastUtils

/**
 * @Org：www.shuhai.com(陕西书海网络科技有限公司)
 * @Author：风不会停息 on 2019/5/31 9:53
 * E_Mail：yh131412hys@163.com
 * Describe：注册
 * Change：
 * @Version：V1.0
 */
class RegisterActivity : BaseActivity(), View.OnClickListener {

    private val TAG = "RegisterActivity"

    override val layoutId: Int
        get() = R.layout.activity_register

    override fun initData() {

    }

    override fun configViews() {

        title_tv.text=resources.getString(R.string.register)
        val spannableString = SpannableString(resources.getString(R.string.user_protocol))
        val colorSpan = ForegroundColorSpan(Color.parseColor("#3296f9"))
        spannableString.setSpan(colorSpan, 10, registerActivity_protocol_tv.text.length, Spannable.SPAN_EXCLUSIVE_INCLUSIVE)
        registerActivity_protocol_tv.text = spannableString

        back_iv.setOnClickListener(this)
        registerActivity_protocol_tv.setOnClickListener(this)
        registerActivity_complete_tv.setOnClickListener(this)
        registerActivity_weChat_tv.setOnClickListener(this)
        registerActivity_qq_tv.setOnClickListener(this)
        registerActivity_weiBo_tv.setOnClickListener(this)
    }

//    public override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
//        super.onActivityResult(requestCode, resultCode, data)
//        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data)
//    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data)
    }

    override fun onClick(v: View?){
        when (v!!.id) {
            R.id.back_iv -> finish()
            R.id.registerActivity_protocol_tv -> startActivity(Intent(this,UserAgreementActivity::class.java))
            R.id.registerActivity_complete_tv -> {

                val userName = registerActivity_userName_et.text.toString().trim()
                if (TextUtils.isEmpty(userName)) {

                    ToastUtils.showToast("请输入用户名")
                    return
                }

                val mailbox = registerActivity_mailbox_et.text.toString().trim()
                if (TextUtils.isEmpty(userName)) {

                    ToastUtils.showToast("请输入邮箱")
                    return
                }
                if (!TextUtils.isEmpty(mailbox) && !RegularExpression.isEmail(mailbox)) {

                    ToastUtils.showToast("请填写有效邮箱")
                    registerActivity_mailbox_et.setText("")
                    return
                }

                val passWord = registerActivity_passWord_et.text.toString().trim()
                if (TextUtils.isEmpty(passWord)) {

                    ToastUtils.showToast("请输入密码")
                    return
                }

                val confirmPassWord = registerActivity_confirmPassWord_et.text.toString().trim()
                if (TextUtils.isEmpty(confirmPassWord)) {

                    ToastUtils.showToast("请输入确认密码")
                    return
                }

                if (passWord != confirmPassWord) {
                    ToastUtils.showToast("两次密码不一致，请重新输入密码")
                    return
                }

                val verificationCode = registerActivity_verificationCode_et.text.toString().trim()
                if (TextUtils.isEmpty(verificationCode)) {

                    ToastUtils.showToast("请输入验证码")
                    return
                }

                RedCloudApis.getInstance().register(userName,passWord,mailbox,verificationCode,object :Observer<ResponseBody>{
                    override fun onComplete() {
                    }

                    override fun onSubscribe(d: Disposable) {
                    }

                    override fun onNext(t: ResponseBody) {

                        val result = String(t.bytes())
                        Log.d("register", result)
                        val jsonObject = JSONObject.parseObject(result)
                        val code = jsonObject.getString("code")

                        if (code == Constants.SYSTEM_OK) {

                            ToastUtils.showToast("注册成功，请去登录")
                            finish()
                        }else{

                            ToastUtils.showToast(jsonObject.getString("msg"))
                        }
                    }

                    override fun onError(e: Throwable) {
                    }
                })
            }
            R.id.registerActivity_weChat_tv -> UMShareAPI.get(this).getPlatformInfo(this, SHARE_MEDIA.WEIXIN, umAuthListener);
            R.id.registerActivity_qq_tv -> UMShareAPI.get(this).getPlatformInfo(this, SHARE_MEDIA.QQ, umAuthListener);
            R.id.registerActivity_weiBo_tv -> UMShareAPI.get(this).getPlatformInfo(this, SHARE_MEDIA.SINA, umAuthListener);
        }
    }

//    对于退出登录，想要删除授权的用户可以使用如下接口：
//    UMShareAPI.get(mContext).deleteOauth(Activity, Platform, authListener);
    private var umAuthListener: UMAuthListener = object : UMAuthListener {
        /**
         * @desc 授权开始的回调
         * @param platform 平台名称
         */
        override fun onStart(platform: SHARE_MEDIA) {

//            if (platform==SHARE_MEDIA.QQ) {
//
//                ToastUtils.showToast("开始")
//            }
        }

        /**
         * @desc 授权成功的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         * @param data 用户资料返回
         */
        override fun onComplete(platform: SHARE_MEDIA, action: Int, data: Map<String, String>) {

            //            1:QQ;2:微博;3:微信
            var loginType = ""
            var province = ""
            var city = ""
//            val area:String

            when (platform) {
                SHARE_MEDIA.QQ -> {

                    //            QQ:[msg=, ret=0, unionid=UID_29E84517EC2BA0C87B43240F6AC3DFFA, gender=男, is_yellow_vip=0, city=咸阳, level=0, openid=E4FE496F6F411FE501019147F57C8208, profile_image_url=http://thirdqq.qlogo.cn/g?b=oidb&k=d1SYtCpnqrbuZuS6zNHcyg&s=100&t=1483305105, accessToken=64814F9482E829C2E4BEDF96F4C2B22A, access_token=64814F9482E829C2E4BEDF96F4C2B22A, uid=E4FE496F6F411FE501019147F57C8208, is_yellow_year_vip=0, province=陕西, screen_name=书海技术, name=书海技术, iconurl=http://thirdqq.qlogo.cn/g?b=oidb&k=d1SYtCpnqrbuZuS6zNHcyg&s=100&t=1483305105, yellow_vip_level=0, expiration=1573440930098, vip=0, expires_in=1573440930098]
                    loginType = Constants.ThirdPartyLoginType.QQ
                    province = data["province"].toString()
                    city = data["city"].toString()
                }
                SHARE_MEDIA.SINA -> {

                    //            SINA:[is_teenager=0, allow_all_act_msg=false, favourites_count=0, urank=9, verified_trade=, weihao=, verified_source_url=, province=61, screen_name=恋--海, id=1931041871, geo_enabled=true, like_me=false, like=false, verified_type=-1, accessToken=2.00dM9gGCdUfTQE2fd7e91e6bK8gz6C, access_token=2.00dM9gGCdUfTQE2fd7e91e6bK8gz6C, pagefriends_count=0, domain=, following=false, name=恋--海, expiration=1569880468185743, cover_image_phone=http://ww1.sinaimg.cn/crop.0.0.640.640.640/549d0121tw1egm1kjly3jj20hs0hsq4f.jpg, status={"created_at":"Mon Aug 05 18:07:24 +0800 2019","id":4401989917940152,"idstr":"4401989917940152","mid":"4401989917940152","can_edit":false,"show_additional_indication":0,"text":"延安新华广播电台","textLength":16,"source_allowclick":0,"source_type":1,"source":"<a href=\"http:\/\/app.weibo.com\/t\/feed\/6ixFkP\" rel=\"nofollow\">延安红云手机<\/a>","favorited":false,"truncated":false,"in_reply_to_status_id":"","in_reply_to_user_id":"","in_reply_to_screen_name":"","pic_urls":[{"thumbnail_pic":"http:\/\/wx4.sinaimg.cn\/thumbnail\/73195c4fly1g5oyo3zdctj2040040dfp.jpg"}],"thumbnail_pic":"http:\/\/wx4.sinaimg.cn\/thumbnail\/73195c4fly1g5oyo3zdctj2040040dfp.jpg","bmiddle_pic":"http:\/\/wx4.sinaimg.cn\/bmiddle\/73195c4fly1g5oyo3zdctj2040040dfp.jpg","original_pic":"http:\/\/wx4.sinaimg.cn\/large\/73195c4fly1g5oyo3zdctj2040040dfp.jpg","geo":null,"is_paid":false,"mblog_vip_type":0,"annotations":[{"client_mblogid":"4a9c10a6-eb38-4d3e-ad60-7ce33b4b50e5"},{"mapi_request":true}],"reposts_count":0,"comments_count":0,"attitudes_count":0,"pending_approval_count":0,"isLongText":false,"reward_exhibition_type":0,"hide_flag":0,"mlevel":0,"visible":{"type":0,"list_id":0},"biz_feature":4294967300,"hasActionTypeCard":0,"darwin_tags":[],"hot_weibo_tags":[],"text_tag_tips":[],"mblogtype":0,"rid":"0","userType":0,"more_info_type":0,"positive_recom_flag":0,"content_auth":0,"gif_ids":"","is_show_bulletin":2,"comment_manage_info":{"comment_permission_type":-1,"approval_comment_type":0}}, idstr=1931041871, follow_me=false, friends_count=96, credit_score=80, gender=男, city=1, profile_url=u/1931041871, description=If you believe you can,then you can., created_at=Sat Jan 22 20:46:10 +0800 2011, remark=, ptype=0, verified_reason_url=, block_word=0, avatar_hd=http://tvax2.sinaimg.cn/crop.9.0.731.731.1024/73195c4fly8fmti2d31twj20ku0kbmzb.jpg?Expires=1565704786&ssig=MzQ4nW2ayj&KID=imgbed,tva, uid=1931041871, mbtype=0, bi_followers_count=3, user_ability=33554432, is_teenager_list=0, verified_reason=, story_read_state=-1, video_status_count=0, mbrank=0, lang=zh-cn, class=1, expires_in=1569880468185743, star=0, allow_all_comment=true, online_status=0, verified=false, profile_image_url=http://tvax2.sinaimg.cn/crop.9.0.731.731.50/73195c4fly8fmti2d31twj20ku0kbmzb.jpg?Expires=1565704786&ssig=TDN2H58xkM&KID=imgbed,tva, block_app=0, url=, avatar_large=http://tvax2.sinaimg.cn/crop.9.0.731.731.180/73195c4fly8fmti2d31twj20ku0kbmzb.jpg?Expires=1565704786&ssig=hNW4y73gyu&KID=imgbed,tva, statuses_count=113, vclub_member=0, followers_count=23, is_guardian=0, iconurl=http://tvax2.sinaimg.cn/crop.9.0.731.731.50/73195c4fly8fmti2d31twj20ku0kbmzb.jpg?Expires=1565704786&ssig=TDN2H58xkM&KID=imgbed,tva, location=陕西 西安, insecurity={"sexual_content":false}, verified_source=, refreshToken=2.00dM9gGCdUfTQE4398d6fda8yCxRJB]

//                    {urank=4, screen_name=用户7053787796, story_read_state=-1, mbrank=0, weihao=, province=100, statuses_count=1, following=false, class=1, follow_me=false, verified_type=-1, id=7053787796, iconurl=http://tvax4.sinaimg.cn/crop.0.0.996.996.50/007HmYqUly8g5xuuyp5uyj30ro0roju4.jpg?Expires=1566195308&ssig=HFIHYd7Na1&KID=imgbed,tva, verified_reason_url=, cover_image_phone=http://ww1.sinaimg.cn/crop.0.0.640.640.640/549d0121tw1egm1kjly3jj20hs0hsq4f.jpg, accessToken=2.00u7y3hHdUfTQE8d3d594a98PwwWbE, domain=, avatar_hd=http://tvax4.sinaimg.cn/crop.0.0.996.996.1024/007HmYqUly8g5xuuyp5uyj30ro0roju4.jpg?Expires=1566195308&ssig=kIXUg9Svt3&KID=imgbed,tva, is_guardian=0, friends_count=5, bi_followers_count=0, location=其他, verified_source=, name=用户7053787796, pagefriends_count=0, verified_reason=, is_teenager_list=0, mbtype=0, verified_source_url=, insecurity={"sexual_content":false}, remark=, url=, city=1000, refreshToken=2.00u7y3hHdUfTQE65ddaa19bc6bAs3C, is_teenager=0, gender=女, block_app=0, ptype=0, block_word=0, star=0, status={"created_at":"Mon Jul 22 13:29:53 +0800 2019","id":4396846648294749,"idstr":"4396846648294749","mid":"4396846648294749","can_edit":false,"show_additional_indication":0,"text":"风风光光 http:\/\/t.cn\/AilH015G","textLength":29,"source_allowclick":0,"source_type":1,"source":"<a href=\"http:\/\/app.weibo.com\/t\/feed\/2hCOBC\" rel=\"nofollow\">书海阅读<\/a>","favorited":false,"truncated":false,"in_reply_to_status_id":"","in_reply_to_user_id":"","in_reply_to_screen_name":"","pic_urls":[],"geo":null,"is_paid":false,"mblog_vip_type":0,"annotations":[{"shooting":1,"client_mblogid":"d19e59ed-4c5f-423a-9d4e-c0376f6e40ff"},{"mapi_request":true}],"reposts_count":0,"comments_count":0,"attitudes_count":0,"pending_approval_count":0,"isLongText":false,"reward_exhibition_type":0,"hide_flag":0,"mlevel":0,"visible":{"type":0,"list_id":0},"biz_feature":0,"hasActionTypeCard":0,"darwin_tags":[],"hot_weibo_tags":[],"text_tag_tips":[],"mblogtype":0,"rid":"0","userType":0,"more_info_type":0,"positive_recom_flag":0,"content_auth":0,"gif_ids":"","is_show_bulletin":2,"comment_manage_info":{"comment_permission_type":-1,"approval_comment_type":0}}, like_me=false, verified=false, allow_all_act_msg=false, lang=zh-cn, expiration=1569880468603428, idstr=7053787796, vclub_member=0, profile_url=u/7053787796, credit_score=80, avatar_large=http://tvax4.sinaimg.cn/crop.0.0.996.996.180/007HmYqUly8g5xuuyp5uyj30ro0roju4.jpg?Expires=1566195308&ssig=AB%2BatoAvtC&KID=imgbed,tva, video_status_count=0, user_ability=0, online_status=0, geo_enabled=true, followers_count=1, profile_image_url=http://tvax4.sinaimg.cn/crop.0.0.996.996.50/007HmYqUly8g5xuuyp5uyj30ro0roju4.jpg?Expires=1566195308&ssig=HFIHYd7Na1&KID=imgbed,tva, like=false, description=, access_token=2.00u7y3hHdUfTQE8d3d594a98PwwWbE, verified_trade=, uid=7053787796, created_at=Thu Mar 28 11:36:42 +0800 2019, favourites_count=0, allow_all_comment=true, expires_in=1569880468603428}

                    loginType = Constants.ThirdPartyLoginType.SINA
                    val address = (data["location"] ?: error("")).split(" ")
                    if (address.isNotEmpty() && address.size >1) {

                        province = address[0]
                        city = address[1]
                    }
                    Log.d(TAG,"$address")
                }
                SHARE_MEDIA.WEIXIN -> {

//                    [country=中国, unionid=o0iKtwtJwsotGxqJvOCazzobJsVg, gender=女, city=西安, openid=ojh_TwGZXBU1ocdARn-UDoCoWCiQ, language=zh_CN, profile_image_url=http://thirdwx.qlogo.cn/mmopen/vi_32/FibfPbxfBkPHqQ6nqiaA6HPwkqqGNaC96j8RDNy8qhLvGbqyIYLn4icgoB7o75nWoH7MeGFxfJpSDgCMCAcVKPv9Q/132, accessToken=24_7PdZv8lMMxfPnX_5jPAgAQ7w_pRJGqsGvwoz-yNhXGKu5xVuB62hgGepUJQvZNbo42UjSJpyPLSrFWc9o4GjLGkQbpv6JjvYMd36g5K3MT8, access_token=24_7PdZv8lMMxfPnX_5jPAgAQ7w_pRJGqsGvwoz-yNhXGKu5xVuB62hgGepUJQvZNbo42UjSJpyPLSrFWc9o4GjLGkQbpv6JjvYMd36g5K3MT8, uid=o0iKtwtJwsotGxqJvOCazzobJsVg, province=陕西, screen_name=全书, name=全书, iconurl=http://thirdwx.qlogo.cn/mmopen/vi_32/FibfPbxfBkPHqQ6nqiaA6HPwkqqGNaC96j8RDNy8qhLvGbqyIYLn4icgoB7o75nWoH7MeGFxfJpSDgCMCAcVKPv9Q/132, expiration=1565957570942, expires_in=1565957570942, refreshToken=24_BRJ6gmn2gUb_cAkN54W5N_lon2N7TKubLwRugWwlvvdGkv8LoE7HdVC4YnuZ9zF0MH8GjxbCP5il2yH6-Ag_7PbptM4D1Sw6PQ_lZcWMDmQ]

                    loginType = Constants.ThirdPartyLoginType.WEIXIN
                    province = data["province"].toString()
                    city = data["city"].toString()
                }
            }

            /*登录成功后，第三方平台会将用户资料传回， 全部会在Map data中返回 ，由于各个平台对于用户资料的标识不同，因此为了便于开发者使用，
            我们将一些常用的字段做了统一封装，开发者可以直接获取，不再需要对不同平台的不同字段名做转换，这里列出我们封装的字段及含义。*/
            /**
             * UShare封装后字段名 QQ原始字段名 微信原始字段名 新浪原始字段名 字段含义 备注
             * uid                openid       unionid        id          用户唯一标识  uid能否实现Android与iOS平台打通，目前QQ只能实现同APPID下用户ID匹配
             *
             * name               screen_name  screen_name  screen_name    用户昵称
             *
             * gender             gender       gender      gender          用户性别        该字段会直接返回男女
             *
             * iconurl            profile_image_url profile_image_url profile_image_url 用户头像
             */
//            Log.d(TAG,"uid:${data["uid"]}-----name:${data["name"]}-----gender:${data["gender"]}-----iconurl:${data["iconurl"]}")

//            0未知 1男 2女
            val sex:String = when {
                data["gender"]=="男" -> Constants.Sex.BOY
                data["gender"]=="女" -> Constants.Sex.GIRL
                else -> Constants.Sex.UNKNOWN
            }

            RedCloudApis.getInstance().getThirdLogin(
                EmojiParser.removeAllEmojis(data["name"]),data["uid"],data["iconurl"],loginType,
                province,city,"",sex,object : Observer<ResponseBody> {

                    override fun onComplete() {

                    }

                    override fun onSubscribe(d: Disposable) {
                    }

                    override fun onNext(t: ResponseBody) {

                        val result = String(t.bytes())
                        if (!TextUtils.isEmpty(result)) {

                            val jsonObject = JSONObject.parseObject(result)
                            val code = jsonObject.getString("code")

                            if (code==Constants.SYSTEM_OK) {

                                val loginEntity = JSONObject.parseObject(result, Login::class.java)
                                UserInfoShardPreference.instance.saveUserInfo(loginEntity.data)
                                EventBus.getDefault().post(MessageEvent(Constants.REFRESH_MINE_FRAGMENT,loginEntity.data))
                                ToastUtils.showToast(getString(R.string.login_success))
                                finish()
                                ActivityUtils.finishActivity(LoginActivity::class.java)
                            }else{

                                ToastUtils.showToast(jsonObject.getString("msg"))
                            }
                        }else{

                            ToastUtils.showToast(getString(R.string.login_failure))
                        }
                    }

                    override fun onError(e: Throwable) {

                        ToastUtils.showToast(getString(R.string.login_failure))
                    }
                })
        }

        /**
         * @desc 授权失败的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         * @param t 错误原因
         */
        override fun onError(platform: SHARE_MEDIA, action: Int, t: Throwable) {

            ToastUtils.showToast("失败")
        }

        /**
         * @desc 授权取消的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         */
        override fun onCancel(platform: SHARE_MEDIA, action: Int) {
            ToastUtils.showToast("取消了")
        }
    }
}
